import $ from 'jquery';
import Button from './Button';


export default class BlockquoteButton extends Button{

  command() {
    let $rootNodes;
    let clearCache;
    let nodeCache;
    $rootNodes = this.editor.selection.rootNodes();
    $rootNodes = $rootNodes.filter((i, node) => !$(node).parent().is('blockquote'));
    this.editor.selection.save();
    nodeCache = [];
    clearCache = () => {
      if (nodeCache.length > 0) {
        $(`<${this.htmlTag}/>`).insertBefore(nodeCache[0]).append(nodeCache);
        return nodeCache.length = 0;
      }
    };
    $rootNodes.each((i, node) => {
      let $node = $(node);
      if (!$node.parent().is(this.editor.body)) return;
      
      if ($node.is(this.htmlTag)) {
        clearCache();
        return $node.children().unwrap();
      } else if ($node.is(this.disableTag) || this.editor.util.isDecoratedNode($node)) {
        return clearCache();
      } else {
        return nodeCache.push(node);
      }
    });
    clearCache();
    this.editor.selection.restore();
    return this.editor.trigger('valuechanged');
  }
}

BlockquoteButton.prototype.name = 'blockquote';
BlockquoteButton.prototype.icon = 'quote-left';
BlockquoteButton.prototype.htmlTag = 'blockquote';
BlockquoteButton.prototype.disableTag = 'pre, table';